import { PayloadAction, createSlice } from '@reduxjs/toolkit';
import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

export interface UserInfo {
    id: string | number;
    name: string;
}

interface UserState {
    token: string | undefined; // 用户tokan
    info: undefined | UserInfo;
}

const initialState: UserState = {
    token: undefined,
    info: undefined,
};

export const userSlice = createSlice({
    name: 'user',
    initialState: initialState,
    reducers: {
        updateToken(state, action: PayloadAction<string | undefined>) {
            state.token = action.payload;
        },
        updateUserInfo(state, action: PayloadAction<UserInfo | undefined>) {
            state.info = action.payload;
        },
    },
});

// 配置 redux-persist 的持久化选项
const persistConfig = {
    key: 'user', // 存储在 localStorage 中的键名
    storage, // 使用 localStorage 作为存储介质
};

export const { updateToken, updateUserInfo } = userSlice.actions;

// export default userSlice.reducer;
export default persistReducer(persistConfig, userSlice.reducer);
